package com.phone.servlet.history;

import com.phone.DBHelper;
import com.phone.entity.Results;
import com.phone.exception.BaseException;
import com.phone.handle.HistoryHandle;
import com.phone.entity.History;
import com.phone.handle.UserHandle;
import com.phone.servlet.BaseServlet;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by tisen on 2017/7/19.
 */
public class Search extends BaseServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        setParamterRequest(request);
        Session session = DBHelper.getSession();
        session.beginTransaction();
        HistoryHandle historyHandle = new HistoryHandle(session);
        UserHandle userHandle = new UserHandle(session);
        Results<History> results = new Results<>();
        try {
            String ownerid = getParamterString("ownerid",false);
            int pageSize = getParamterInt("pagesize",true,10);
            int page = getParamterInt("page",true,1);
            userHandle.getById(ownerid);
            List<History> histories = historyHandle.search(ownerid);
            int size = histories.size();
            int fromIndex = pageSize * (page - 1) <= size ? pageSize * (page - 1) : size;
            int toIndex = pageSize * page <= size ? pageSize * page : size;
            if ((page - 1) * pageSize > size) {
                results = new Results(ERROR, "page beyond", histories.size(), pageSize, page, null);
            } else {
                results = new Results(SUCCESS, "search history successful", histories.size(), pageSize, page,
                        histories.subList(fromIndex, toIndex));
            }
            session.getTransaction().commit();
        } catch (HibernateException exception) {
            exception.printStackTrace();
            results.setReason("sql error");
            session.getTransaction().rollback();
        } catch (BaseException exception) {
            exception.printStackTrace();
            results.setReason(exception.getMessage());
            session.getTransaction().rollback();
        } catch (Exception e) {
            results.setReason(e.getMessage());
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen())
                session.close();
            out(response, results);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
